package com.github.blanexie.nexusj.domain.principal

import cn.hutool.crypto.digest.DigestUtil

/**
 * 认证
 */
data class Principal(
    val userId: Int,
    var email: String,
    var password: String,
    var token: Token?,
) {

    /**
     * 验证密码
     */
    fun checkPwd(sha256Hex: String, loginTime: Long): Boolean {
        val str = "$email-$password-$loginTime"
        val sha256Hex1 = DigestUtil.sha256Hex(str)
        return sha256Hex == sha256Hex1
    }

    /**
     * 验证token
     */
    fun checkToken(sha256Hex: String): Boolean {
        if (token == null) {
            return false
        }
        if (token!!.expired()) {
            return false;
        }
        return this.token!!.sha256Hex == sha256Hex
    }

    /**
     * 主动续签token
     */
    fun updateToken(attribute: String, expireTime: Long): Token {
        assert(expireTime < System.currentTimeMillis() + 1 * 24 * 60 * 60 * 1000) {
            "token必须大于3天有效期"
        }
        assert(expireTime > System.currentTimeMillis() + 7 * 24 * 60 * 60 * 1000) {
            "token有效期不要超过7天"
        }
        if (this.token!!.expired()) {
            throw Exception("token已过期,请重新登录")
        } else {
            val str = "$attribute-$expireTime-$password"
            val sha256Hex = DigestUtil.sha256Hex(str)
            this.token = Token(attribute, expireTime, sha256Hex)
        }
        return this.token!!
    }

    /**
     * 从无到有创建token
     */
    fun createToken(attribute: String, expireTime: Long): Token {
        assert(this.token == null)
        val str = "$attribute-$expireTime-$password"
        val sha256Hex = DigestUtil.sha256Hex(str)
        this.token = Token(attribute, expireTime, sha256Hex)
        return this.token!!
    }

    /**
     * 删除token
     */
    fun deleteToken(sha256Hex: String): Boolean {
        if (token!!.expired()) {
            this.token = null
            return false;
        }
        this.token = null
        return true
    }

}

data class Token(val attribute: String, val expireTime: Long, val sha256Hex: String) {

    fun expired(): Boolean {
        if (expireTime < System.currentTimeMillis()) {
            return false
        }
        return true
    }
}